package com.xxx.lease.web.app.custom.interceptor;

import com.xxx.lease.common.context.LoginUser;
import com.xxx.lease.common.context.LoginUserContext;
import com.xxx.lease.common.exception.LeaseException;
import com.xxx.lease.common.result.ResultCodeEnum;
import com.xxx.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /*
    *   拦截请求的方法
    * */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("access_token");

        if (token == null || token.isEmpty()) {

            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else {
            //解析token （会验证token是否过期）
            Claims claims = JwtUtil.parseToken(token);

            Long userId = claims.get("userId", Long.class);

            String userName = claims.get("userName", String.class);

            LoginUserContext.saveLoginUser(new LoginUser(userId, userName));
        }
        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.removeLoginUser();

    }
}
